<template>
  <div style="text-align: center">
    <el-button text @click="dialogVisible = true" style="float: right">添加关键词</el-button>
    <el-dialog v-model="dialogVisible" title="添加文章关键词" width="30%">
      <div class="addDomain" @click="addKeyword">搜索不到对应的关键词?</div>
      <el-input v-model="keyword" style="width: 200px;margin-right: 10px"></el-input>
      <el-button @click="getKeywords(keyword)">搜索</el-button>
      <br><br>
      <hr>
      <keyword-search-result-component v-model="keywords"/>

      <template #footer>
      <span class="dialog-footer">
        <el-button @click="canal">取消</el-button>
        <el-button type="primary" @click="add">添加</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {provide, ref} from 'vue'
import {search, addKeywordApi} from '@/apis/keyword.js'
import {ElMessage} from "element-plus";
import KeywordSearchResultComponent from "./KeywordSearchResultComponent.vue";

const dialogVisible = ref(false)
const keyword = ref('')
const keywords = ref([]) // 域名查询结果集合
const index = ref(-1)
provide('index', index)

const getKeywords = (searchToken) => {
  if (!searchToken) {
    ElMessage.error('请输入查询关键词')
    return
  }
  search(searchToken).then(resp => {
    console.log(resp.data)
    if (resp.data.code === 200) {
      index.value = -1
      keywords.value = resp.data.data
    }
  })
}
import {defineModel} from "vue";
const content = defineModel()
console.log(content)
const isNotExistInContent = (kw) => {
  const list = content.value.keywords;
  for (let i = 0; i < list.length; i++) {
    if (list[i].id === kw.id) {
      return false;
    }
  }
  return true
}

const init = () => {
  index.value = -1
  dialogVisible.value = false
  keyword.value = ''
  keywords.value = []
}

const canal = () => {
  init()
}

const add = () => {
  const i = index.value
  if (i >= 0 && i < keywords.value.length) {
    const kw = keywords.value[i]
    if (isNotExistInContent(kw)) {
      content.value.keywords.push(kw)
    }
    init()
  } else {
    ElMessage.error('请选择领域')
  }
}

const addKeyword = () => {
  const text = prompt('请输入需要添加的关键词, 之后在重新查询')
  if (text) {
    const keyword = {name: text}
    addKeywordApi(keyword).then(resp => {
      console.log(resp.data)
      if (resp.data.code === 200) {
        ElMessage.success('添加成功')
      } else {
        ElMessage.error(resp.data.msg)
      }
    })
  } else {
    ElMessage.info('操作取消')
  }
}
</script>
<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

.addDomain:hover {
  text-decoration-line: underline;
  cursor: pointer;
  color: blue;
}
</style>
